package com.zzyl.serve.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.serve.domain.NursingPlan;
import com.zzyl.serve.domain.NursingProjectPlan;
import com.zzyl.serve.dto.NursingPlanDto;
import com.zzyl.serve.mapper.NursingPlanMapper;
import com.zzyl.serve.service.INursingPlanService;
import com.zzyl.serve.service.INursingProjectPlanService;
import com.zzyl.serve.vo.NursingPlanVo;
import com.zzyl.serve.vo.NursingProjectPlanVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.zzyl.common.constant.CacheConstants.NURSING_PLAN_KEY;

/**
 * 护理计划Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-04
 */
@Service
public class NursingPlanServiceImpl extends ServiceImpl<NursingPlanMapper, NursingPlan> implements INursingPlanService {
    @Autowired
    private NursingPlanMapper nursingPlanMapper;

    @Autowired
    private INursingProjectPlanService nursingProjectPlanService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增护理计划（Day6-课堂2）
     *
     * @param nursingPlanDto 护理计划
     * @return 结果
     */
    @Override
    @Transactional
    public int insertNursingPlan(NursingPlanDto nursingPlanDto) {
        // 1、保存护理计划的基本数据
        NursingPlan nursingPlan = new NursingPlan();
        BeanUtils.copyProperties(nursingPlanDto, nursingPlan);
        save(nursingPlan);

        // 2、批量保存护理计划关联的护理项目集合信息
        int result = 0;
        List<NursingProjectPlan> projectPlans = nursingPlanDto.getProjectPlans();
        if (ObjectUtil.isNotEmpty(projectPlans)) {
            projectPlans.forEach(item -> item.setPlanId(nursingPlan.getId()));
            boolean saveResult = nursingProjectPlanService.saveBatch(projectPlans);
            result = saveResult ? 1 : 0;
        }
        redisTemplate.delete(NURSING_PLAN_KEY);
        return result;
    }

    /**
     * 查询护理计划（Day6-课堂3）
     *
     * @param id 护理计划主键
     * @return 护理计划
     */
    @Override
    public NursingPlanVo selectNursingPlanById(Long id) {
        // 1、查询护理计划基本信息
        NursingPlan nursingPlan = getById(id);
        NursingPlanVo planVo = new NursingPlanVo();
        BeanUtils.copyProperties(nursingPlan, planVo);

        // 2、查询护理计划关联的护理项目集合信息
        // 2.1、查询
        List<NursingProjectPlan> list = nursingProjectPlanService.lambdaQuery()
                .eq(NursingProjectPlan::getPlanId, id)
                .list();

        // 2.2、转化为voList
        List<NursingProjectPlanVo> voList = list.stream().map(p -> {
            NursingProjectPlanVo vo = new NursingProjectPlanVo();
            BeanUtils.copyProperties(p, vo);
            vo.setProjectId(String.valueOf(p.getProjectId()));
            vo.setExecuteCycle(String.valueOf(p.getExecuteCycle()));
            return vo;
        }).collect(Collectors.toList());
        planVo.setProjectPlans(voList);

        // 3、返回vo
        return planVo;
    }

    /**
     * 查询护理计划列表
     *
     * @param nursingPlan 护理计划
     * @return 护理计划
     */
    @Override
    public List<NursingPlan> selectNursingPlanList(NursingPlan nursingPlan) {
        return nursingPlanMapper.selectNursingPlanList(nursingPlan);
    }

    /**
     * 修改护理计划
     *
     * @param nursingPlanDto 护理计划
     * @return 结果
     */
    @Override
    @Transactional
    public int updateNursingPlan(NursingPlanDto nursingPlanDto) {
        // 1、修改护理计划关联的护理项目列表
        List<NursingProjectPlan> projectPlans = nursingPlanDto.getProjectPlans();
        // 1.1、判断护理计划关联的护理项目列表是否为空
        if (ObjectUtil.isNotEmpty(projectPlans)) {
            // 1.2、不为空，删除该护理计划关联的护理项目列表
            // delete from nursing_project_plan where plan_id = ?
            nursingProjectPlanService.remove(new LambdaQueryWrapper<NursingProjectPlan>()
                    .eq(NursingProjectPlan::getPlanId, nursingPlanDto.getId()));

            // 1.3、再批量保存该护理计划关联的护理项目列表
            projectPlans.forEach(item -> item.setPlanId(nursingPlanDto.getId()));
            nursingProjectPlanService.saveBatch(projectPlans);
        }

        // 2、修改护理计划基本信息
        NursingPlan nursingPlan = new NursingPlan();
        BeanUtils.copyProperties(nursingPlanDto, nursingPlan);
        redisTemplate.delete(NURSING_PLAN_KEY);
        return updateById(nursingPlan) ? 1 : 0;
    }

    /**
     * 批量删除护理计划
     *
     * @param id 需要删除的护理计划主键
     * @return 结果
     */
    @Override
    public int deleteNursingPlanByIds(Long id) {
        this.removeById(id);
        boolean remove = nursingProjectPlanService.remove(new LambdaQueryWrapper<NursingProjectPlan>().eq(NursingProjectPlan::getPlanId, id));
        redisTemplate.delete(NURSING_PLAN_KEY);
        return remove ? 1 : 0;

    }

    /**
     * 删除护理计划信息
     *
     * @param id 护理计划主键
     * @return 结果
     */
    @Override
    public int deleteNursingPlanById(Long id) {
        boolean b = removeById(id);
        redisTemplate.delete(NURSING_PLAN_KEY);
        return b ? 1 : 0;
    }

    @Override
    public List<NursingPlan> listAll(LambdaQueryWrapper<NursingPlan> queryWrapper) {
        //判断当前缓存中是否存在数据
        List<NursingPlan> list = (List<NursingPlan>) redisTemplate.opsForValue().get(NURSING_PLAN_KEY);
        //如果存在则直接返回数据
        if (ObjectUtil.isNotEmpty(list)) {
            return list;
        }
        //如果不存在则查询数据库，并把数据保存到缓存中。
        list = this.list(queryWrapper);
        redisTemplate.opsForValue().set(NURSING_PLAN_KEY, list);
        return list;
    }
}
